package sfeir.ergosum.emulator;

import java.io.File;
import java.io.FilenameFilter;

import sfeir.ergosum.AddContactActivity;
import sfeir.ergosum.R;
import sfeir.ergosum.tools.RGBMonochromeBitmapSource;

import com.google.zxing.ReaderException;
import com.google.zxing.Result;
import com.google.zxing.qrcode.QRCodeReader;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class AddContactQrActivity extends Activity implements OnClickListener {

    private static final int SELECT_FILE = 1;
    private Bitmap bitmap = Bitmap.createBitmap(320, 240,
            Bitmap.Config.ARGB_8888);
    public Canvas canvas = new Canvas(bitmap);
    public ImageView image;
    private ImageView chart;

    public Handler handler = new Handler();

    // private WebcamThread webcamThread;
    private QRCodeReader mQRReader;
    // private boolean active = false;
    // private SocketCamera cs = new SocketCamera("10.0.2.2", 9889, 320, 240,
    // true);
    private String[] picNames;
    private ProgressDialog scanningDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.camera);

        mQRReader = new QRCodeReader();

        image = (ImageView) findViewById(R.id.camera);
        image.setImageBitmap(bitmap);
        image.setVisibility(View.GONE);
        chart = (ImageView) findViewById(R.id.chart);

        Button button = (Button) findViewById(R.id.ButtonWebcam);
        button.setOnClickListener(this);
        Button pickPng = (Button) findViewById(R.id.ButtonPickPng);
        pickPng.setText("Scan a QR in the SD Card");
        pickPng.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog(SELECT_FILE);
            }
        });

        showDialog(SELECT_FILE);
    }

    @Override
    public void onClick(View v) {
        // if (!active) {
        // webcamThread = new WebcamThread(this, cs);
        // webcamThread.start();
        // } else {
        // webcamThread.terminate();
        // handler.post(new BitmapScanner(cs.bitmap));
        //
        // }
        // active = !active;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            setResult(RESULT_CANCELED);
            finish();
            return true;

        } else if (keyCode == KeyEvent.KEYCODE_FOCUS
                || keyCode == KeyEvent.KEYCODE_CAMERA) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case SELECT_FILE:
            return new AlertDialog.Builder(this).setTitle("Choisir image")
                    .setItems(getPicNames(),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                        int which) {
                                    Bitmap map = BitmapFactory
                                            .decodeFile("/sdcard/"
                                                    + picNames[which]);
                                    dismissDialog(SELECT_FILE);
                                    scanningDialog = ProgressDialog.show(
                                            AddContactQrActivity.this,
                                            "Scanning ...", "reading code",
                                            true, false);

                                    // WebcamActivity.this.handler
                                    // .post(new BitmapScanner(map));
                                    new Thread(new BitmapScanner(map)).start();
                                    chart.setImageBitmap(map);
                                }
                            }).create();

        default:
            return null;
        }
    }

    public String[] getPicNames() {
        String[] picNames = new File("/sdcard").list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String filename) {
                return filename.endsWith("png") || filename.endsWith("jpg");
            }
        });
        this.picNames = picNames;
        return picNames;
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        super.onPrepareDialog(id, dialog);
    }

    private class BitmapScanner implements Runnable {

        private Bitmap bSource;

        public BitmapScanner(Bitmap bitmap) {
            this.bSource = bitmap;
        }

        @Override
        public void run() {
            Result result = null;

            RGBMonochromeBitmapSource source = new RGBMonochromeBitmapSource(
                    bSource);
            try {
                result = mQRReader.decode(source);
            } catch (ReaderException e) {
            }

            scanningDialog.dismiss();
            if (null != result) {
//                Intent intent = new Intent(getIntent().getAction());
                Intent intent = new Intent(AddContactQrActivity.this, AddContactActivity.class);
//                Intent intent = new Intent(AddContactQrActivity.this, AddContactURLActivity.class);
                intent.putExtra("SCAN_RESULT", result.toString());
                intent.putExtra("SCAN_RESULT_FORMAT", result.getBarcodeFormat()
                        .toString());
                setResult(Activity.RESULT_OK, intent);
                finish();
            } else
                Toast.makeText(AddContactQrActivity.this,
                        (result == null) ? "Failed" : result.getText(), 3000)
                        .show();
        }
    }
}